#include "LocalServer.h"
#include <SFML/Network.hpp>
#include <iostream>
#include "Helpers.h"
#include "Tank.h"
#include "Application.h"
#include "KeyboardController.h"
#include "RemoteController.h"


cat::LocalServer::LocalServer(int port)
	: _port(port), 
	_newClient(new sf::TcpSocket())
{
	std::cout << "Creation of the server ... ";
	_listener.setBlocking(false);
	_newClient->setBlocking(false);
	if (_listener.listen(_port) != sf::Socket::Done)
	{
		std::cerr<<"Failed"<<std::endl;
		return;
	}

	std::cout<< "Done" << std::endl;
}


cat::LocalServer::~LocalServer(void)
{
	_listener.close();
	if(_newClient != NULL) delete _newClient;
}

void cat::LocalServer::think(void)
{
	TrackNewConnections();
	TrackNewClientInputs();
}

void cat::LocalServer::connect()
{
	cat::Application& application = cat::Application::current();

	cat::Tank* tank = new cat::Tank();
	cat::ControllerBase* playerController = new cat::KeyboardController(*tank);
	application.registerTank(tank);
	application.registerController(playerController);
}

void cat::LocalServer::disconnect(void)
{
	
}

void cat::LocalServer::TrackNewConnections(void)
{
	if (_listener.accept(*_newClient) == sf::Socket::Done)
	{
		std::cout<<"A client is being connected at "<< _newClient->getRemoteAddress() << ":" << _newClient->getRemotePort() <<std::endl;
		cat::Application& application = cat::Application::current();
		
		cat::Tank* tank = new cat::Tank();
		cat::RemoteController* remoteController = new cat::RemoteController(*tank, _newClient);
		application.registerTank(tank);
		application.registerController(remoteController);

		// New connection tracker
		_newClient = new sf::TcpSocket();
		_newClient->setBlocking(false);
	}
}

void cat::LocalServer::TrackNewClientInputs(void)
{
	
}